package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

type ProgressWriter struct {
	Total       int64
	Current     int64
	ProgressBar string
}

func (pw *ProgressWriter) Write(p []byte) (int, error) {
	n := len(p)
	pw.Current += int64(n)
	pw.printProgress()
	return n, nil
}

func (pw *ProgressWriter) printProgress() {
	percent := float64(pw.Current) / float64(pw.Total) * 100
	barLength := 50
	progress := int(percent / 2)

	fmt.Printf("\r[%s%s] %.2f%%",
		strings.Repeat("=", progress),
		strings.Repeat(" ", barLength-progress),
		percent)
}

func DownloadWithProgress(url, filename string) error {
	// 检查文件是否已存在
	if _, err := os.Stat(filename); err == nil {
		fmt.Printf("文件 %s 已存在，跳过下载\n", filename)
		return nil
	}

	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	out, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer out.Close()

	pw := &ProgressWriter{
		Total:   resp.ContentLength,
		Current: 0,
	}

	_, err = io.Copy(out, io.TeeReader(resp.Body, pw))
	fmt.Println() // 换行
	return err
}
